import { defineStore } from 'pinia';

import { loginApi, logoutApi } from '@/api/system/authorization';
import type { LoginData } from '@/api/system/authorization/types';
import router from '@/router';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { addServerRoutes } from '@/utils/router-helper';

import useAppStore from '../app';
import useDictStore from '../dict';
import useTabBarStore from '../tab-bar';
import { UserState } from './types';

const useUserStore = defineStore('operation-user', {
  persist: { storage: localStorage },
  state: (): UserState => ({
    userId: '',
    username: '',
    realName: '',
    role: '',
    roles: [],
    permissions: [],
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await loginApi(loginForm);
        this.setInfo(res as UserState);
        setToken(res.accessToken);
        // 初始化服务器端菜单
        const appStore = useAppStore();
        await appStore.fetchServerMenu();
        if (appStore.appAsyncMenus.length) {
          addServerRoutes(router);
        }
        // 初始化数据字典
        const dictStore = useDictStore();
        await dictStore.initDict();
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      this.resetInfo();
      clearToken();
      removeRouteListener();

      const appStore = useAppStore();
      appStore.clearServerMenu();

      const tabBarStore = useTabBarStore();
      tabBarStore.resetTabList();
    },
    // Logout
    async logout() {
      try {
        await logoutApi();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
